#include <string.h>
#include <math.h>
#include <stdlib.h>

#include "Unit.h"
#include "SynthUnits.h"

void Noise::ar(unsigned port, sample_t *buf, jack_nframes_t len, Options options)
{
   for (jack_nframes_t i = 0; i < len; i ++)
   {
      sample_t s = ((float) rand()) / RAND_MAX * 2 - 1; /* random in [-1; 1] */
      if (options.isAddition)
         buf[i] += s;
      else
         buf[i] = s;
   }

   /* debug */
   if (options.isDebugBuffer)
   {
      for (unsigned i = 0; i < len; i ++)
         DEBUG("Noise: %f\n", buf[i]);
      DEBUG("\n");
   }
}

void Gain::ar(unsigned port, sample_t *buf, jack_nframes_t len, Options options)
{
   if (port >= getAudioPortCount())
      textException("Wrong port number");

   readFromPort(port, buf, len, options);

   /* gain the buffer */
   for (jack_nframes_t i = 0; i < len; i ++)
   {
      buf[i] = buf[i] * mGain;
   }

   /* debug */
   if (options.isDebugBuffer)
   {
      for (unsigned i = 0; i < len; i ++)
         DEBUG("Gain: %f\n", buf[i]);
      DEBUG("\n");
   }
}

void SinOsc::ar(unsigned portNum, sample_t *buf, jack_nframes_t len, Options opt)
{
   JackClient j = JackClient::getInstance();

   for (jack_nframes_t i = 0; i < len; i ++)
   {
      sample_t s = sin((double) (mPhase ++) / j.getSampleRate() * mFreq * 2 * M_PI);
      if (opt.isAddition)
         buf[i] += s;
      else
         buf[i] = s;

      if (opt.isDebugBuffer)
         DEBUG("SinOsc: %f -> %f\n", (double) mPhase, s);
   }
   if (opt.isDebugBuffer)
      puts("");
}
